import Vue from 'vue';
import Router from 'vue-router';

Vue.use(Router);

//路由路径
const routes = [
    {
        path: '/',
        redirect: '/LoginSys',
    },
    {
        path: '/LoginSys',
        name: 'LoginSys',
        component: () => import('../components/LoginSys'),
    },
    {
        path: '/NavigationBar',
        name: 'NavigationBar',
        component: () => import('../views/NavigationBar'),
        children: [
            {path: '/',redirect:'/NavigationBar/GradesQuery'},
            {
                path: '/NavigationBar/GradesQuery',
                name: 'GradesQuery',
                component: () => import('../views/GradesQuery')
            },
            {
                path: '/NavigationBar/StudentPage',
                name: 'StudentPage',
                component:()=>import('../views/StudentPage')
            },
            {
                path: '/NavigationBar/SubjectPage',
                name: 'SubjectPage',
                component:()=>import('../views/SubjectPage')
            },
            {
                path: '/NavigationBar/TeacherPage',
                name: 'TeacherPage',
                component:()=>import('../views/TeacherPage')
            },
            {
                path: '/NavigationBar/LoginSettings',
                name: 'LoginSettings',
                component:() =>import('../views/LoginSettings')
            },
            {
                path: '/NavigationBar/InformationManage',
                name: 'InformationManage',
                component:() =>import('../views/InformationManage')
            }
        ]
    }

];

//先进行初始化路由
const router = new Router({
    mode: 'history',
    routes,
});

//解决：Vue 重复点击相同路由造成控制台报错
const VueRouterPush = Router.prototype.push
Router.prototype.push = function push (to) {
    return VueRouterPush.call(this, to).catch(err => err)
}

// 路由导航守卫，为了防止未登录就进入系统
router.beforeEach((to, from, next) => {
    // 1.如果访问的是登录页面（无需权限），直接放行
    if (to.path === '/LoginSys') return next()
    // 2.如果访问的是有登录权限的页面，先要获取token
    const tokenStr = window.sessionStorage.getItem('token')
    // 2.1如果token为空，强制跳转到登录页面；否则，直接放行
    if (!tokenStr) return next('/LoginSys')
    next()
});

// 导出路由
export default router;